package middleware

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"user_bff/model"
	"user_bff/pkg"
)

func CheckUserLogin() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("token")
		if len(token) == 0 {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"code": -1,
				"msg":  "token为空",
				"data": nil,
			})
			return
		}
		accessToken, err := pkg.CheckAccessToken(token)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"code": -1,
				"msg":  "token解析失败",
				"data": nil,
			})
			return
		}
		user := model.User{}
		json.Unmarshal([]byte(accessToken), &user)
		c.Set("userId", user.Id)
		c.Next()
	}
}
